package com.fxz.oauth.validation;

import com.fxz.oauth.annotation.ValidEmail;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author Fxz
 * @version 1.0
 * @date 2021-08-03 16:38
 *
 * 固定写法 实现ConstraintValidator接口 两个泛型 第一个泛型表示作用在的自定义的注解 第二个泛型表示注解加在String字段上
 */
public class EmailValidator implements ConstraintValidator<ValidEmail,String> {

    /**
     * 自定义的正则表达式 用于校验邮件格式
     */
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";


    /**
     * 初始化时执行
     * @param constraintAnnotation
     */
    @Override
    public void initialize(ValidEmail constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    /**
     * 用于校验的逻辑
     * @param s
     * @param constraintValidatorContext
     * @return
     */
    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        return validateEmail(s);
    }

    /**
     * 正则表达式校验邮箱地址
     * @param email 邮箱地址
     * @return
     */
    private boolean validateEmail(final String email){
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();

    }

}
